//
//  VipCardViewController.m
//  fitnessmanage
//
//  Created by 众拳科技 on 2017/10/30.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//

#import "VipCardViewController.h"
#import "YZPullDownMenu.h"
#import "YZMenuButton.h"
#import "YCXMenu.h"
#import "VipCardModel.h"
#import "SearchView.h"
#import "VipCardClassSelectViewController.h"
#import "VipCardStateSelectViewController.h"
#import "VipInfoCardTableViewCell.h"
#import "SelectVipCardClassViewController.h"
#import "VipCardInfoViewController.h"
#import "RenewalCardRemindViewController.h"
#import "VipCardExportViewController.h"
#import "VipCardModel.h"

@interface VipCardViewController ()<YZPullDownMenuDataSource,UITableViewDelegate,
                                    UITableViewDataSource,UITextFieldDelegate>{
        
    int startIndex;
    
    int pageSize;
}

@property (nonatomic, strong) NSArray *titles;

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property (nonatomic , strong) NSMutableArray *rightItems;

@property(nonatomic,strong)NoDataView *noDataView;

@property(nonatomic,strong)NSString *searchCond;

@property(nonatomic,strong)VipCardClassSelectViewController *vc1;

@end

@implementation VipCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = BackGroundColor;
    
    self.title = @"会员卡";
    
//    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"icon_navadd"]
//                                                                               imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
//    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    [self createSubView];
    
    [NotificationCenter addObserver:self selector:@selector(loadStartData) name:@"ReloadVenueCard" object:nil];
    
    [NotificationCenter addObserver:self selector:@selector(conditionClick:) name:YZUpdateMenuTitleNote object:nil];
}

-(void)createSubView{
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = BackGroundColor;
    [self.view addSubview:bgView];
    
    SearchView *searchView = [[SearchView alloc] init];
    searchView.placeholder = @"请输入会员名、会员卡号、手机号";
    searchView.backgroundColor = CSWhiteColor;
    searchView.delegate = self;
    [bgView addSubview:searchView];
    
    [bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.width.mas_equalTo(self.view);
    }];
    
    [searchView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(40);
        
        make.edges.mas_equalTo(bgView).insets(UIEdgeInsetsMake(10, 20, 10, 20));
    }];
    
    // 创建下拉菜单
    YZPullDownMenu *menu = [[YZPullDownMenu alloc] init];
    menu.backgroundColor = CSWhiteColor;
    menu.coverColor = [CSBlackColor colorWithAlphaComponent:0.4];
    menu.separateLineColor = LineBackGroundColor;
    [self.view addSubview:menu];
    [menu mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(bgView.mas_bottom);
        make.left.mas_equalTo(bgView);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(self.view).multipliedBy(2.0 / 3);
    }];
    
    // 设置下拉菜单代理
    menu.dataSource = self;
    
    // 初始化标题
    _titles = @[@"会员卡种类",@"会员卡状态"];
    
    // 添加子控制器
    [self setupAllChildViewController];
    
    //续卡提醒
    UIButton *noticeBtn = [[UIButton alloc] init];
    [noticeBtn setTitle:@"续卡提醒"];
    [noticeBtn setTitleColor:CSColorFromRGB(0x0a0a0a)];
    noticeBtn.titleLabel.font = MidFont;
    noticeBtn.backgroundColor = CSWhiteColor;
    [noticeBtn addTarget:self action:@selector(noticeBtnClick)];
    [self.view addSubview:noticeBtn];
    [noticeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(menu.mas_right);
        make.top.mas_equalTo(menu);
        make.bottom.mas_equalTo(menu).offset(-1);
        make.right.mas_equalTo(self.view);
    }];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 200;
    [tableView registerClass:[VipInfoCardTableViewCell class] forCellReuseIdentifier:@"VipInfoCardTableViewCell"];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.backgroundColor = CSClearColor;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.width.mas_equalTo(self.view);
        make.top.mas_equalTo(menu.mas_bottom);
    }];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyHidden = YES;
    
    
    MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
    tableView.mj_header = mj_head;
    tableView.mj_footer = footer;
    [tableView.mj_header beginRefreshing];
    
//    UIButton *addVenueVipBtn = [[UIButton alloc] init];
//    [addVenueVipBtn setImage:@"suspend_add"];
//    [addVenueVipBtn addTarget:self action:@selector(addCardClass)];
//    [self.view addSubview:addVenueVipBtn];
//    [addVenueVipBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
//
//        make.right.mas_equalTo(self.view).offset(-10);
//
//        make.bottom.mas_equalTo(self.view).offset(-30);
//    }];
    
}

#pragma mark 下拉
-(void)loadStartData{
    
    startIndex = 1;
    
    pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    startIndex = startIndex + 1;
    
    [self loadData];
}

-(void)loadData{
    
    //GET_Leave_DeleteLeave
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    
    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];

    [params setValue:self.searchCond forKey:@"Condition"];

    [params setObject:[NSString stringWithFormat:@"%d",startIndex] forKey:@"page"];

    [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
    
    [HTTPTool GET:GET_SalesOrder_SalesOrderListData parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  if (resultArray.count > 0) {
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }
                  
                  self.noDataView = [NoDataView shareInstance];
                  
                  [self.noDataView hideInView:self.view];
                  
                  if (startIndex == 1) {
                      
                      self.dataSource = [NSMutableArray arrayWithArray:resultArray];
                      
                      if (self.dataSource.count == 0) {
                          
                          self.noDataView = [NoDataView shareInstance];
                          
                          [self.noDataView showInView:self.view];
                      }
                  }
                  else{
                      
                      [self.dataSource addObjectsFromArray:resultArray];
                  }
                  
                  self.vc1.dataSource = self.dataSource;
                  
//                  [self.view bringSubviewToFront:self.tableView];
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma mark - 添加子控制器
- (void)setupAllChildViewController
{
    VipCardClassSelectViewController *vc1 = [[VipCardClassSelectViewController alloc] init];
    vc1.colCount = 0;
    self.vc1 = vc1;
    
    VipCardStateSelectViewController *vc2 = [[VipCardStateSelectViewController alloc] init];
    vc2.colCount = 1;
    
    vc2.titleArray = [NSMutableArray arrayWithObjects:@"默认",@"已停卡", nil];
    
    [self addChildViewController:vc1];
    [self addChildViewController:vc2];
}

#pragma mark - YZPullDownMenuDataSource
// 返回下拉菜单多少列
- (NSInteger)numberOfColsInMenu:(YZPullDownMenu *)pullDownMenu
{
    return _titles.count;
}

// 返回下拉菜单每列按钮
- (UIButton *)pullDownMenu:(YZPullDownMenu *)pullDownMenu buttonForColAtIndex:(NSInteger)index
{
    YZMenuButton *button = [YZMenuButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = MidFont;
    [button setTitle:_titles[index] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:25 /255.0 green:143/255.0 blue:238/255.0 alpha:1] forState:UIControlStateSelected];
    [button setImage:[UIImage imageNamed:@"more_icon_arrow_down"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"more_icon_arrow_up"] forState:UIControlStateSelected];
    
    return button;
}

// 返回下拉菜单每列对应的控制器
- (UIViewController *)pullDownMenu:(YZPullDownMenu *)pullDownMenu viewControllerForColAtIndex:(NSInteger)index
{
    return self.childViewControllers[index];
}

// 返回下拉菜单每列对应的高度
- (CGFloat)pullDownMenu:(YZPullDownMenu *)pullDownMenu heightForColAtIndex:(NSInteger)index
{
    // 第1列 高度
    if (index == 0) {
        
        return self.view.height;
    }
    
    return 220;
    
}

#pragma mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count ;
}

#pragma mark UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 40;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headView = [[UIView alloc] init];
    headView.backgroundColor = CSWhiteColor;
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = MidBigFont;
    titleLabel.text = @"会员卡种数：";
    titleLabel.textColor = TextColor1;
    [headView addSubview:titleLabel];
    [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.left.mas_equalTo(headView).offset(15);
        make.centerY.mas_equalTo(headView);
    }];
    
    UILabel *countLabel = [[UILabel alloc] init];
    countLabel.font = MidBigFont;
    countLabel.text = [NSString stringWithFormat:@"%lu",(unsigned long)self.dataSource.count];
    [headView addSubview:countLabel];
    [countLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.centerY.mas_equalTo(titleLabel);
        make.left.mas_equalTo(titleLabel.mas_right).offset(5);
    }];
    return headView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    VipInfoCardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VipInfoCardTableViewCell"];

    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.row];
    
    VipCardModel *vipCardModel = [VipCardModel mj_objectWithKeyValues:dict];
        
    cell.vipCardModel = vipCardModel;
    
    cell.selectRow = indexPath.row;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    VipCardInfoViewController *vipCardInfoVC = [[VipCardInfoViewController alloc] init];
    
    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.row];
    
    VipCardModel *vipCardModel = [VipCardModel mj_objectWithKeyValues:dict];
    
    if ([vipCardModel.Status intValue] == 4003) {
        
        [MBProgressHUD showText:@"该会员卡已经过期"];
        
        return;
    }
    
    vipCardInfoVC.selectRow = indexPath.row;
    
    vipCardInfoVC.vipCardModel = vipCardModel;
    
//    [self.navigationController pushViewController:vipCardInfoVC animated:YES];
}


#pragma mark 开卡
-(void)addCardClass{
    
    SelectVipCardClassViewController *selectVipCardVC = [[SelectVipCardClassViewController alloc] init];
    [self.navigationController pushViewController:selectVipCardVC animated:YES];
}

#pragma mark 续卡提醒
-(void)noticeBtnClick{
    
    RenewalCardRemindViewController *renewalCardRemindVC = [[RenewalCardRemindViewController alloc] init];
    [self.navigationController pushViewController:renewalCardRemindVC animated:YES];
}

#pragma mark 右侧菜单
-(void)rightBtnClick{
    
    
    
    if ([YCXMenu isShow]){
        
        [YCXMenu dismissMenu];
    }
    else{
        
        __weak typeof(self)weakSelf = self;
        
        [YCXMenu setHasShadow:YES];
        [YCXMenu setBackgrounColorEffect:YCXMenuBackgrounColorEffectSolid];
        [YCXMenu setTintColor:CSWhiteColor];
        [YCXMenu setSelectedColor:CSClearColor];
        [YCXMenu setSeparatorColor:[[UIColor grayColor] colorWithAlphaComponent:0.5]];
        //        [YCXMenu setMenuItemMarginY:15];
        [YCXMenu setTitleFont:[UIFont systemFontOfSize:16.0]];
#warning czq
        CGFloat top = CZQ_StatusBarHeight + CZQ_NavigationBarHeight;
        [YCXMenu showMenuInView:[UIApplication sharedApplication].keyWindow fromRect:CGRectMake(weakSelf.view.frame.size.width - 50, top - 5, 50, 0) menuItems:weakSelf.rightItems selected:^(NSInteger index, YCXMenuItem *item) {

            if ([item.title isEqualToString:@"会员卡管理"]) {

                [MBProgressHUD showText:@"暂未开通"];
            }
            else{

                VipCardExportViewController *vipCardExportVC = [[VipCardExportViewController alloc] init];

                [weakSelf.navigationController pushViewController:vipCardExportVC animated:YES];
            }
            NSLog(@"%@",item);
        }];
    }
}


#pragma mark 搜索条件响应通知
-(void)conditionClick:(NSNotification *)sender{
    
    NSDictionary *userInfo = sender.userInfo;
    
    NSString *title = [userInfo objectForKey:@"title"];
    
    self.searchCond = title;
    
    [self loadStartData];
}

#pragma mark UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField*)textField{
    
    self.searchCond = textField.text;

    [self loadStartData];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField

{
    
    self.searchCond = textField.text;
    
    [self loadStartData];
    
    [textField endEditing:YES];
    
    return YES;
    
}

#pragma mark Get

- (NSMutableArray *)rightItems {
    if (!_rightItems) {
        
        //set item
        _rightItems = [@[
                         [YCXMenuItem menuItem:@"会员卡管理"
                                         image:nil
                                           tag:100
                                      userInfo:@{@"title":@"Menu"}],
                         [YCXMenuItem menuItem:@"会员卡导出"
                                         image:nil
                                           tag:101
                                      userInfo:@{@"title":@"Menu"}],
                         
                         ] mutableCopy];
    }
    return _rightItems;
}

-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
        
    }
    
    return _dataSource;
}


-(void)dealloc{
    
    [NotificationCenter removeObserver:self];
}
@end
